<?php

namespace App\Http\Middleware;

use Closure;
use \App\User;

class PermissionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $req = \Route::current()->getActionName();

        
        $user = User::find(session('user')->id);
        if($user->username=='admin'){
             return $next($request);
        }
        $roles = $user -> roles()->get();
        $arr = [];
        foreach ($roles as $key => $value) {
           $pers = $value->per;
           foreach ($pers as $key => $vv) {
               $arr[] = $vv->description;
           }
        }
        $arr = array_unique($arr);
        if(in_array($req, $arr)){
             return $next($request);
        }else{
            return back();
        }
    }
}
